const app = getApp();
import grace from "../../../utils/grace.js";
// socket 连接插件
const io = require('../../../utils/weapp.socket.io.js');
const io_client = io(app.globalData.websocket_url);
const innerAudioContext = wx.createInnerAudioContext();

grace.page({
    data: {
        school_name: '',
        class_id: 0,
        class_name: '',
        attendance_date: '',
        attendances: [],
        attendances_temp: []
    },
    onLoad: function () {
        let that = this;
        let d = new Date();
        that.$data = {
            'school_name': wx.getStorageSync('school_name'),
            'class_id': wx.getStorageSync('class_id'),
            'class_name': wx.getStorageSync('class_name'),
            'attendance_date': d.getFullYear() + '年' + (d.getMonth() + 1) + "月" + d.getDate() + '日'
        }

        io_client.on('connect', function() {
            // 连接成功时的事件
            io_client.emit('login', {username: wx.getStorageSync('partner_id')});
        });

        io_client.on('disconnect', function() {
            // 断开连接时的事件
            io_client.emit('logout', {username: wx.getStorageSync('partner_id')});
        });

        io_client.on("clock", function(resp){
            // 打卡信息显示在页面上
            that.$data.attendances_temp.push(resp);
            that.$data.attendances = that.$data.attendances_temp;
            that.$data.attendances.reverse();

            // 语音播报
            innerAudioContext.src = app.globalData.audio_url + 'clock_' + resp['class_id'] + '_' + resp['student_id'] + '.mp3';
            innerAudioContext.play();
        });
    },
    onShow: function () {
        let that = this;
        let school_id = wx.getStorageSync('school_id')
        wx.showLoading({
            title: '加载中...',
        })
        let url = app.globalData.api + '/api/v1.0/student/ferryLogs/' + that.$data.class_id;
        that.$http.get(url, {token: wx.getStorageSync('token')}).then((res) => {
            if (res.data.code == 0) {
                that.$data.attendances_temp = res.data.data;
                that.$data.attendances = res.data.data;
            } else {
                that.$data.attendances = [];
            }
            wx.hideLoading();

            // 进入房间
            io_client.emit('join', {school_id: school_id, room: wx.getStorageSync('class_id')});
        }).catch(err => {
            console.log(err.status, err.message);
        });
    },
    onHide: function () {
        let school_id = wx.getStorageSync('school_id')
        // 离开班级
        io_client.emit('leave', {school_id: school_id, username: wx.getStorageSync('partner_id'), room: wx.getStorageSync('class_id')});
    }
})